package com.ServletDemo.servletText05;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/servletDemo08")
public class servletDemo08 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取图片绝对路径
        String realPath = getServletContext().getRealPath("/img/1.jpg");
        //读取图片
        BufferedInputStream bis =new BufferedInputStream(new FileInputStream(realPath));
        //Content-Type消息头名称 支持的类型 application/octet-stream 消息头参数,应用的类型为字符流
        resp.setHeader("Content-Type","application/octet-stream");
        //Content-Disposition 消息头名称 处理的形式  attachment;filename=1.jpg 消息头参数 附件形式进行处理 指定下载文件的名称
        resp.setHeader("Content-Disposition","attachment;filename=1.jpg");
        //响应到服务器
        ServletOutputStream out = resp.getOutputStream();

        byte[] by= new byte[1024];
        int bys;
        while ((bys=bis.read(by))!=-1){
            out.write(by,0,bys);
        }
        bis.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
